package pl.edu.pw.polygen.modeler.server.xml;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.StringWriter;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

import org.apache.tools.ant.filters.StringInputStream;

public class MarshallService {
	
	private JAXBContext context;
	private Marshaller marshaller;
	private Unmarshaller unmarshaller;
	
	public MarshallService(){
		try{
			context = JAXBContext.newInstance(PolygenData.class);
			marshaller = context.createMarshaller();
			marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
			marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
			unmarshaller = context.createUnmarshaller();
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	
	public String marshall(PolygenData data){
		try {
			StringWriter stringWriter = new StringWriter();
			marshaller.marshal(data, stringWriter);
			return stringWriter.toString();
		} catch (Exception e) {
			System.err.println("cos nie tak");
			e.printStackTrace();
		}
		return null;
	}
	
	public PolygenData unmarshall(String data){
		try{
			InputStream is = new ByteArrayInputStream(data.getBytes("UTF-8"));
			PolygenData polygenData = (PolygenData)unmarshaller.unmarshal(is);
			return polygenData;
		}catch(Exception e){
			e.printStackTrace();
		}
		return null;
	}
	
	
}
